package org.lc.gateway.util;

import cn.hutool.core.util.ObjUtil;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class SchemeUtil {

    public static final String START_TIME = "startTime";

    public static final String HTTP_SCHEME = "http";

    public static final String HTTPS_SCHEME = "https";


    public static boolean isNoHttpAndHttps(String scheme) {
        return !HTTP_SCHEME.equalsIgnoreCase(scheme) && !HTTPS_SCHEME.equals(scheme);
    }


    public static Flux<DataBuffer> getCacheFlux(DataBuffer dataBuffer, ServerWebExchange exchange, boolean endRelease) {
        byte[] bytes = new byte[dataBuffer.readableByteCount()];
        dataBuffer.read(bytes);
        DataBufferUtils.release(dataBuffer);
        return Flux.defer(() -> {
            DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
            DataBufferUtils.retain(buffer);
            var mJust = Mono.just(buffer);
            if (endRelease) {
                return mJust.doFinally(s -> {
                    DataBufferUtils.release(buffer);
                });
            }
            return mJust;
        });
    }

    public static String getServiceId(ServerWebExchange exchange) {
        /* 获取微服务路由信息 */
        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        if (ObjUtil.isNotNull(route) && ObjUtil.isNotNull(route.getUri().getHost())) {
            return route.getUri().getHost().toLowerCase();
        }
        return null;
    }
}
